package com.chance.cc.crawler.development.scripts.haoyisheng;

import com.alibaba.fastjson.JSONObject;
import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRecord;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Json;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.core.tags.LabelTag;
import com.chance.cc.crawler.core.tags.crawler.CrawlerBusinessTags;
import com.chance.cc.crawler.core.tags.crawler.CrawlerResultTags;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.chance.cc.crawler.development.scripts.allfeild.AICCommonField.*;
import static com.chance.cc.crawler.development.scripts.allfeild.AutoVMCommonField.Tag_Field_Topic_Type;

/**
 * @Author Zhao.Hhuan
 * @Date Create in 2021/7/5 11:09
 * @Description
 *      好医生
 **/
public class HaoYiShengCrawlerScript extends CrawlerCommonScript {

    private static Logger log = LoggerFactory.getLogger(HaoYiShengCrawlerScript.class);
    private static final String DOMAIN = "haoyisheng";
    private static final String REQUEST_AGAIN_TAG = DOMAIN +"_request_retry";
    private static final String SEARCH_KW_SOURCE_URL = "searchKwSourceUrl";
    private static final String PREFIX = "http://haoyisheng.com";

    private static final String SEARCH_URL = "http[s]*://haoyisheng.com/search\\S*";
    private static final String ITEM_URL = "http[s]*://haoyisheng.com/[a-z\\/]*/\\d+";

    /**
     * 脚本domain定义
     *
     * @return
     */
    @Override
    public String domain() {
        return DOMAIN;
    }

    /**
     * 进入脚本的正则列表
     */
    @Override
    public void initUrlRegulars() {
        addUrlRegular(SEARCH_URL);
        addUrlRegular(ITEM_URL);
    }

    /**
     * 是否执行脚本 ： 输入数据检查，合格的才进入脚本
     *
     * @param crawlerRequestRecord
     * @return
     */
    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        return true;
    }

    @Override
    public List<CrawlerRecord> prepareRequest(CrawlerRequestRecord requestRecord, List<CrawlerRequestRecord> supportSourceRecords) {
        List<CrawlerRecord> crawlerRecords = new ArrayList<>();

        for (CrawlerRequestRecord supportSourceRecord : supportSourceRecords) {
            String url = supportSourceRecord.getHttpRequest().getUrl();
            if (url.contains("keys")) {
                initKeyword(requestRecord, supportSourceRecord, crawlerRecords);
            }
        }
        return crawlerRecords;
    }

    /**
     * 解析链接方法
     *
     * @param crawlerRequestRecord
     * @param httpPage
     * @return
     */
    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks = new ArrayList<CrawlerRequestRecord>();
        String requestUrl = crawlerRequestRecord.getHttpRequest().getUrl();

        if (!httpPage.isDownloadSuccess() || (httpPage.getStatusCode() != 200)) {
            log.error("{} status code : {}", crawlerRequestRecord.getHttpRequest().getUrl(), httpPage.getStatusCode());
            if (httpPage.getStatusCode() != 404) {
                requestAgainCrawlerRecord(parsedLinks, crawlerRequestRecord);
            }
            crawlerRequestRecord.setNeedWashPage(false);
            return parsedLinks;
        }

        if(requestUrl.matches(SEARCH_URL)){
            searchUrlRecord(crawlerRequestRecord,httpPage,parsedLinks);
        }

        if(requestUrl.matches(ITEM_URL)){
            itemUrlRecord(crawlerRequestRecord,httpPage,parsedLinks);
        }

        return parsedLinks;
    }

    private void searchUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks) {
        String result = httpPage.getHtml().xpath("//p[@class=\"result\"]").get();
        String keyword = (String) httpPage.getRequest().getExtras().get("keyword");
        if (StringUtils.isNotBlank(result) && result.contains("共有 0 条")) {
            log.error("{} search result is 0!", keyword);
            return;
        }
        //未发现下一页

        //详情页
        List<Selectable> nodes = httpPage.getHtml().xpath("//div[@class=\"c_tabs\"]/div/ul/li").nodes();
        for (Selectable node : nodes) {
            String itemUrl = node.xpath("./a/@href").get();
//            .//span[@class="mt_time"]
            String releaseTime = node.xpath(".//span[@class=\"c_tabs_sl\"]").get();
            if(StringUtils.isBlank(itemUrl) || StringUtils.isBlank(releaseTime)){
                continue;
            }

            itemUrl =PREFIX + itemUrl;
            try {
                long releaseTimeToLong = washTimeToLong(releaseTime);
                CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                        .itemPageRequest(crawlerRequestRecord)
                        .httpUrl(itemUrl)
                        .releaseTime(releaseTimeToLong)
                        .recordKey(itemUrl + keyword)
                        .copyBizTags()
                        .copyResultTags()
                        .build();
                parsedLinks.add(itemRecord);
            } catch (ParseException e) {
                log.error(e.getMessage());
            }
        }
    }

    private void itemUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks){
        CrawlerResultTags resultTags = crawlerRequestRecord.tagsCreator().resultTags();
        if(resultTags.hasDataType(CrawlerEnum.CrawlerDataType.comment)){
            resultTags.getCategoryTag().removeLabelTag("comment");
        }
    }

    private void initKeyword(CrawlerRequestRecord requestRecord, CrawlerRequestRecord supportSourceRecord, List<CrawlerRecord> crawlerRecords) {
        HttpPage internalDownloadPage = supportSourceRecord.getInternalDownloadPage();
        Map<String, Object> extras = requestRecord.getHttpRequest().getExtras();
        if (extras == null) {
            return;
        }
        String searchKwSourceUrl = (String) extras.get(SEARCH_KW_SOURCE_URL);
        if (StringUtils.isBlank(searchKwSourceUrl)) {
            log.error("searchKw source url can not is null!");
            return;
        }
        Json json = internalDownloadPage.getJson();
        String msg = json.jsonPath($_type + ".msg").get();
        if (!"success".equals(msg)) {
            log.error("keyword page [{}] download error!", internalDownloadPage.getRequest().getUrl());
            return;
        }

        List<String> all = json.jsonPath($_type + ".content").all();
        for (String data : all) {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String keyword = jsonObject.getString("keyword");

            try {
                String itemUrl = searchKwSourceUrl.replace("%s", URLEncoder.encode(keyword, "UTF-8"));
                CrawlerRequestRecord turnRecord = CrawlerRequestRecord.builder()
                        .turnPageRequest(requestRecord)
                        .httpUrl(itemUrl)
                        .releaseTime(System.currentTimeMillis())
                        .notFilterRecord()
                        .httpHeads(requestRecord.getHttpRequest().getHeaders())
                        .copyBizTags()
                        .copyResultTags()
                        .build();
                turnRecord.tagsCreator().bizTags().addKeywords(keyword);
                turnRecord.getHttpRequest().addExtra("keyword", keyword);
                crawlerRecords.add(turnRecord);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage());
            }
        }
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRecord, HttpPage page) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        CrawlerResultTags resultTags = crawlerRecord.tagsCreator().resultTags();
        if(resultTags.hasDataType(CrawlerEnum.CrawlerDataType.article)){
            crawlerDataList.add(washArticle(crawlerRecord,page));
        }

        if(resultTags.hasDataType(CrawlerEnum.CrawlerDataType.interaction)){
            crawlerDataList.add(washInteraction(crawlerRecord,page));
        }
        return crawlerDataList;
    }

    private CrawlerData washArticle (CrawlerRequestRecord crawlerRecord, HttpPage httpPage){
        try{
            String itemUrl = httpPage.getRequest().getUrl();
            String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1);
            String title = httpPage.getHtml().xpath("//h1[@class=\"article_title\"]").get();
            String source = httpPage.getHtml().xpath("//span[@class=\"source\"]").get();
            source = StringUtils.isNotBlank(source) && source.contains("来源：") ? source.split("：")[1] : "";
            String releaseTime = httpPage.getHtml().xpath("//span[@class=\"date\"]").get();

            List<String> all = httpPage.getHtml().xpath("//div[@class=\"article_cnt\"]/p//text()").all();
            StringBuffer contentBf = new StringBuffer();
            for (String s : all) {
                if(StringUtils.isBlank(s)){
                    continue;
                }
                contentBf.append(s).append(" ");
            }
            List<String> tags = httpPage.getHtml().xpath("//div[@class=\"article_tags\"]/a").all();

            CrawlerData crawlerData = CrawlerData.builder()
                    .data(crawlerRecord, httpPage)
                    .dataId(StringUtils.joinWith("-", crawlerRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("article"))
                    .url(itemUrl)
                    .releaseTime(washTimeToLong(releaseTime))
                    .addContentKV(Field_Content, getContentNoEs(contentBf.toString()))
                    .addContentKV(Field_Title, getContentNoEs(title))
                    .addContentKV(Field_Source, source)
                    .build();
            if(tags != null &&tags.size() > 0){
                crawlerData.tagsCreator().bizTags().addCustomKV(Tag_Field_Topic_Type,tags);
            }
            return crawlerData;
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

    private CrawlerData washInteraction (CrawlerRequestRecord crawlerRecord, HttpPage httpPage){
        try{
            String itemUrl = httpPage.getRequest().getUrl();
            String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1);

            String views = httpPage.getHtml().xpath("//span[@class=\"views\"]").get();
            views = StringUtils.isBlank(views) ? "0" : views;
            String likes = httpPage.getHtml().xpath("//span[@class=\"likes\"]").get();
            likes = StringUtils.isBlank(likes) ? "0" : likes;
            String releaseTime = httpPage.getHtml().xpath("//span[@class=\"date\"]").get();
            CrawlerData crawlerData = CrawlerData.builder()
                    .data(crawlerRecord, httpPage)
                    .parentId(StringUtils.joinWith("-", crawlerRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .dataId(StringUtils.joinWith("-", crawlerRecord.getDomain(), CrawlerEnum.CrawlerDataType.interaction.enumVal(), articleKey))
                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("interaction"))
                    .url(itemUrl)
                    .releaseTime(washTimeToLong(releaseTime))
                    .addContentKV(Field_I_Likes,likes)
                    .addContentKV(Field_I_Views, views)
                    .build();
            return crawlerData;
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }
    private static String getContentNoEs(String content) {
        if (StringUtils.isBlank(content)) {
            return "";
        }

        int time = 0;
        String result = content;
        while (content.contains("&") && content.contains(";")) {
            result = StringEscapeUtils.unescapeHtml(result);
            if (time >= 5) {
                break;
            }
            time++;
        }
        return result;
    }

    @Override
    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }

    private void requestAgainCrawlerRecord(List<CrawlerRequestRecord> crawlerRequestRecords, CrawlerRequestRecord crawlerRecord) {
        CrawlerBusinessTags crawlerBusinessTags = crawlerRecord.tagsCreator().bizTags();
        int count = 0;
        if (crawlerBusinessTags.hasKVTag(REQUEST_AGAIN_TAG)) {
            count = (int) crawlerBusinessTags.getCategoryTag().getKVTag(REQUEST_AGAIN_TAG).getVal();
            if (count >= 5) {
                log.error("sina download page the number of retries exceeds the limit" +
                        ",request url {},detail is [{}]", crawlerRecord.getHttpRequest().getUrl(),JSONObject.toJSONString(crawlerRecord));
                return;
            }
        }

        String requestUrl = crawlerRecord.getHttpRequest().getUrl();
        CrawlerRequestRecord crawlerRequestRecord = null;
        LabelTag type = crawlerRecord.tagsCreator().requestTags().getCategoryTag().getLabelTags().get("turn_page_item_request");
        if (type == null) {
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .notFilterRecord()
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        } else {
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .itemPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        }

        crawlerRequestRecord.setNeedWashPage(crawlerRecord.isNeedWashPage());
        crawlerRequestRecord.setNeedParsedPage(crawlerRecord.isNeedParsedPage());
        crawlerRequestRecord.getHttpRequest().setHeaders(crawlerRecord.getHttpRequest().getHeaders());
        crawlerRequestRecord.getHttpRequest().setExtras(crawlerRecord.getHttpRequest().getExtras());
        crawlerRequestRecord.tagsCreator().bizTags().addCustomKV(REQUEST_AGAIN_TAG, ++count);
        crawlerRequestRecords.add(crawlerRequestRecord);
    }

    private static String washContent(String regx, String input) {
        Pattern compile = Pattern.compile(regx);
        Matcher matcher = compile.matcher(input);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return null;
    }

    private static long washTimeToLong(String time) throws ParseException {
        if (StringUtils.isBlank(time)) {
            return 0;
        }

        time = time.trim();
        if (time.matches("\\d{2}月\\d{2}日") || time.matches("\\d{2}月\\d{2}日 \\d{2}:\\d{2}")) {
            time = LocalDate.now().getYear() + time;
        }
        return DateUtils.parseDate(time, "yyyy-MM-dd HH:mm:ss", "发表于 yyyy/MM/dd HH:mm", "yyyyMM月dd日", "yyyy-MM-dd HH:mm", "yyyyMM月dd日 HH:mm", "日期：yyyy-MM-dd", "yyyy年MM月dd日 HH:mm",
                "时间：yyyy-MM-dd HH:mm:ss").getTime();
    }

    public static void main(String[] args) {
        String s = "https://a.sina.cn/t/author/19656553/";

        String substring = s.substring(s.substring(0, s.length() - 1).lastIndexOf("/") + 1);
        System.out.println(substring);


    }
}
